import { useRequest } from "ahooks";
import { message } from "antd";
import useLoginModel from "../model/useLoginModel";
import { getPathWithParams } from "../utils";

export interface RequestParams {
    url: string
    successAction?: Function | string
    businessErrorAction?: Function
    serviceErrorAction?: Function
}

interface _RequestParams extends RequestParams {
    method: string
}
export interface ResponseTypes {
    code: string
    content: any
    msg: string
}

const useRequestMethod = ({ method, url, successAction, businessErrorAction, serviceErrorAction }: _RequestParams) => {
    const userInfo = useLoginModel?.data
    const token = userInfo?.token
    let headers: any = { 'content-type': 'application/json;charset=UTF-8' }
    if (userInfo && token) {
        const user = userInfo.user
        headers["token"] = token
        headers["username"] = user?.username;
        headers["kk-userId"] = user?.username;
        headers["kk-appId"] = "lease";
    }
    const isGet = method.toUpperCase() === "GET"
    return useRequest((params) => ({
        url: isGet && params ? getPathWithParams(url, params) : url,
        method,
        body: !isGet && params ? JSON.stringify(params) : null,
        headers
    }), {
        manual: true,
        onSuccess: (result: ResponseTypes) => {
            if (result.code === '0') {
                typeof successAction === 'string' ? message.success(successAction) : successAction && successAction(result)
            } else {
                businessErrorAction ? businessErrorAction(result) : message.error(result.msg)
            }
        },
        onError: (error) => {
            serviceErrorAction ? serviceErrorAction(error) : message.error(error.message)
        }
    });
}

export const usePostRequest = (params: RequestParams) => useRequestMethod({ ...params, method: 'post' })
export const useGetRequest = (params: RequestParams) => useRequestMethod({ ...params, method: 'get' })